Error Boundary
https://ja.react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary
子要素で例外がスローされた際に、フォールバック UI を表示する機能
try ... catch のようなイメージ
React ではコンポーネントを提供していないので、実現するには react-error-boundary などのサードパーティ製のライブラリが必要
code:tsx
<ErrorBoundary fallback={<NotFound />}>
<Page />
</ErrorBoundary>
一応、自分で実装することも可能
code:ts
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
logErrorToMyService(error, info.componentStack);
}
render() {
if (this.state.hasError) {
return this.props.fallback;
}
return this.props.children;
}
}
#React